package cn.bytest.netty.serialize;

import cn.bytets.rpc.api.code.ChannelByteBuf;
import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.io.InputStream;

public class ChannelBufferInput extends InputStream {

    private final ChannelByteBuf buffer;

    private final int startIndex;

    private final int endIndex;

    public ChannelBufferInput(ChannelByteBuf buffer){
        /**
         * readableBytes 为可读字节长度(this.writerIndex - this.readerIndex)
         */
        this(buffer,buffer.readableBytes());
    }
    public ChannelBufferInput(ChannelByteBuf buffer,int length){
        if (length<=0){
            throw new IllegalArgumentException("length: " + length);
        }
        this.buffer = buffer;
        this.startIndex = buffer.readerIndex();
        this.endIndex = startIndex+length;
        buffer.markReaderIndex();
    }
    public int readBytes() {
        return buffer.readerIndex() - startIndex;
    }

    @Override
    public int available() throws IOException {
        return endIndex - buffer.readerIndex();
    }

    @Override
    public void mark(int readlimit) {
        buffer.markReaderIndex();
    }

    @Override
    public boolean markSupported() {
        return true;
    }

    @Override
    public int read() throws IOException {
        if (!readable()) {
            return -1;
        }
        //return buffer.readByte() & 0xff;
        return -1;
    }
    private boolean readable(){
        return (buffer.writerIndex()-buffer.readerIndex())>0;
    }
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int available = available();
        if (available == 0) {
            return -1;
        }

        len = Math.min(available, len);
        buffer.readBytes(b, off, len);
        return len;
    }

    @Override
    public void reset() throws IOException {
        buffer.resetReaderIndex();
    }

    @Override
    public long skip(long n) throws IOException {
//        if (n > Integer.MAX_VALUE) {
//            return skipBytes(Integer.MAX_VALUE);
//        } else {
//            return skipBytes((int) n);
//        }
        return -1L;
    }

    private int skipBytes(int n) throws IOException {
        int nBytes = Math.min(available(), n);
        //buffer.skipBytes(nBytes);
        return nBytes;
    }
}
